﻿//------------------------------------------------------------------------------
//  
//------------------------------------------------------------------------------
#region Imported Namespaces
using System;
using System.IO;
using System.Xml.Serialization;
using System.Data;
using System.Configuration;
using System.Collections;

using SSRS;
using PHSRAG.Insight21.Reports;
using PHSRAG.Insight21.InsightUtilities;
using Utils = PHSRAG.Insight21.InsightUtilities;
using PHSRAG.Insight21.SearchContext;
//using UserContext = PHSRAG.Insight21.Context.UserContext;
using AgreementsConstants = PHSRAG.Insight21.InsightUtilities.Constants.AgreementsConstants;

#endregion

namespace PHSRAG.Insight21.Agreements.Reports
{


    public class sqlExpenseReport : sqlReport
    {
        private const string CategoryKey = "categoryID";
        private const string AcctKey = "accountNumber";
        private const string UseIDKey = "domainuserid";
        private const string MonthStartingDateKey = "expensefromdate";
        private const string MonthEndingDateKey = "expensetodate";
        private const string expOverviewReportName = "Agmt_ExpenseOverviewReport";
        private const string expDetailReportName = "Agmt_ExpenseDetailReport";
        private string FundNumber;
        private ExpenseOverview expenseOverview;
        private ExpenseDetails expenseDetails;
        private string CategoryName;
        private ArrayList AcctMonArray;

        public sqlExpenseReport(string pageUrl)
            : base(pageUrl)
        {
        }

        public override ParameterValue[] setParameters(ref string rptName)
        {
            Hashtable h = pageCachePolicy.GetCachedObject(Keys.ExpenseInfoPageKey) as Hashtable;
            FundNumber = (h == null || h[Keys.FundNumberKey] == null) ? string.Empty : (string)h[Keys.FundNumberKey];
            bool IsDetail = FundNumber != string.Empty;

            reportTitle = IsDetail ? "Expense Details" : "Expense Overview";


            if (!IsDetail)
            {
                expenseOverview = Policy.ResultsCache.GetObject(cachePolicy, ExpenseOverview.CacheKey) as ExpenseOverview;
                expenseOverview.LoadCategoryAccounts(Utility.DataAccess.ConnectionString, searchCriteria, Session.SessionID, searchCriteria[CategoryKey] == null ? 0 : Convert.ToInt32(searchCriteria[CategoryKey]));

                reportSource = expenseOverview.GetDataContainer().Copy();

                CategoryName = searchCriteria[CategoryKey] == null ? "" : expenseOverview.GetDataContainer().Tables["Category"].Select("CategoryID='" + searchCriteria[CategoryKey] + "'")[0]["CategoryName"].ToString();
                rptName = rptFormat == "Excel" ? expOverviewReportName + "Excel" : expOverviewReportName;
            }
            else
            {
                expenseDetails = Policy.ResultsCache.GetObject(cachePolicy, ExpenseDetails.CacheKey) as ExpenseDetails;
                expenseDetails.LoadCategoryAccounts(Utility.DataAccess.ConnectionString, searchCriteria, Session.SessionID, searchCriteria[CategoryKey] == null ? 0 : Convert.ToInt32(searchCriteria[CategoryKey]), FundNumber);

                reportSource = expenseDetails.GetDataContainer().Copy();

                CategoryName = searchCriteria[CategoryKey] == null ? "" : expenseDetails.GetDataContainer().Tables["Category"].Select("CategoryID='" + searchCriteria[CategoryKey] + "'")[0]["CategoryName"].ToString();
                rptName = rptFormat == "Excel" ? expDetailReportName + "Excel" : expDetailReportName; //expDetailReportName;
            }

            processDSNullField();
            getAccountMonths();
            updMonthsOfAllTables();

            reportCriteria = loadCriteria(searchCriteria);
            reportResultCount = "0";

            return base.setParameters(ref rptName);

        }

        /// <summary>
        ///  
        /// <param name="searchCriteria">Object containing search criteria.</param>
        /// <returns>A string representation of search criteria. </returns>
        protected override string loadCriteria(SearchCriteria searchCriteria)
        {

            DateTime asOfDate = (DateTime)((DataSet)cachePolicy.GetCachedObject(RefreshDatesControlKey)).Tables[0].Rows[0]["glPostAsOfDate"];
            return string.Format(
                "{0}{1}{2}{3}{4}"
                , searchCriteria[AcctKey] == null ? "" : "Account Number|" + searchCriteria[AcctKey] + ";"
                , searchCriteria[CategoryKey] == null ? "" : "Category |" + CategoryName.Trim() + ";"
                , searchCriteria[MonthStartingDateKey] == null ? "" : "Month from||" + searchCriteria[MonthStartingDateKey] + ";"
                , searchCriteria[MonthEndingDateKey] == null ? "" : "Month to|" + searchCriteria[MonthEndingDateKey] + ";"
                , "Last GL Post|" + asOfDate.ToShortDateString() + ";"
             );

        }


        private void getAccountMonths()
        {
            AcctMonArray = new ArrayList();

            foreach (DataRow dr in rptSource.Tables["Accounts"].Rows)
            {
                AcctMonArray.Add(dr["ExpenseMonth"]);
            }
            //Add months for following tables if amount > 0
            string[] sumTableNames = { "Accounts", "DirectCosts", "IndirectCosts", "TotalCosts", "Revenue" };
            foreach (DataTable dt in rptSource.Tables)
            {
                if (Array.IndexOf(sumTableNames, dt.TableName) >= 0) //Find the tablenames in  rptSource
                {
                    foreach (DataRow dr in dt.Rows)
                    {

                        if (!Convert.IsDBNull(dr[0]) && Math.Abs(Convert.ToDecimal(dr[0])) > 0)
                        {
                            DateTime t = Convert.ToDateTime(dr["ExpenseMonth"]);
                            if (!AcctMonArray.Contains(t) && t > DateTime.MinValue)
                            {
                                AcctMonArray.Add(t);
                                InsertIntoAccountTable(t);
                            }
                        }
                    }
                }
            }
        }

        private void updMonthsOfAllTables()
        {
            string[] sumTableNames = { "DirectCosts", "IndirectCosts", "TotalCosts", "Revenue", "CashBalance" };
            foreach (DataTable dt in rptSource.Tables)
            {

                if (Array.IndexOf(sumTableNames, dt.TableName) >= 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        DateTime t = Convert.ToDateTime(dr["ExpenseMonth"]);
                        if (!AcctMonArray.Contains(t))
                            dr.Delete();
                    }
                    dt.AcceptChanges();

                }
            }
            rptSource.AcceptChanges();
        }

        private void InsertIntoAccountTable(DateTime monthsToBeAddedInAccountTable)
        {

            int iCount = 0;
            int maxRowCount = rptSource.Tables["Accounts"].Rows.Count;

            DateTime currentDate = DateTime.MinValue;
            DataSet ds = rptSource.Copy();
            //create a new row
            DataRow drAccount = rptSource.Tables["Accounts"].NewRow(); // .Rows[iCount];
            drAccount["CategoryName"] = rptSource.Tables["Accounts"].Rows[iCount]["CategoryName"];
            drAccount["CategoryID"] = rptSource.Tables["Accounts"].Rows[iCount]["CategoryID"];
            drAccount["ExpenseMonth"] = monthsToBeAddedInAccountTable;
            drAccount["SortOrder"] = rptSource.Tables["Accounts"].Rows[iCount]["SortOrder"];
            drAccount["AccountNumber"] = rptSource.Tables["Accounts"].Rows[iCount]["AccountNumber"];
            drAccount["ExpenseAmount"] = 0;
            drAccount["AccountId"] = rptSource.Tables["Accounts"].Rows[iCount]["AccountId"];

            foreach (DataRow dr in ds.Tables["Accounts"].Rows)
            {
                currentDate = Convert.ToDateTime(rptSource.Tables["Accounts"].Rows[iCount]["ExpenseMonth"]);
                if (iCount < maxRowCount-1)
                {
                    if (monthsToBeAddedInAccountTable < currentDate)
                    {

                        rptSource.Tables["Accounts"].Rows.InsertAt(drAccount, iCount);
                        break;
                    }

                }
                else if (iCount == maxRowCount - 1 && monthsToBeAddedInAccountTable < currentDate)
                {
                    rptSource.Tables["Accounts"].Rows.InsertAt(drAccount, iCount );
                    break;
                }
                else if (iCount == maxRowCount - 1 && monthsToBeAddedInAccountTable > currentDate)
                {
                    rptSource.Tables["Accounts"].Rows.InsertAt(drAccount, maxRowCount);
                    break;
                }

                iCount++;
            }
        }
    }
}
